/**
 * 增强型段落编辑器组件
 * 集成AI Copilot功能，提供实时建议和智能补全
 */

import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Row, Col, Card, Button, Space, Tooltip, message, Dropdown, Menu } from 'antd';
import {
  BulbOutlined,
  EditOutlined,
  SaveOutlined,
  UndoOutlined,
  RedoOutlined,
  FormatPainterOutlined,
  CheckOutlined,
  CloseOutlined,
  RightOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import { CopilotSidebar } from '@/components/copilot/CopilotSidebar';
import { CopilotSuggestion } from '@/types/brainstorm';
import { aiCopilotService } from '@/services/ai-copilot.service';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import './style.css';

interface EnhancedParagraphEditorProps {
  sessionId: string;
  outlineNodeId: string;
  outlineNodeTitle: string;
  initialContent?: string;
  wordCountTarget?: number;
  onSave?: (content: string) => void;
  onCancel?: () => void;
}

export const EnhancedParagraphEditor: React.FC<EnhancedParagraphEditorProps> = ({
  sessionId,
  outlineNodeId,
  outlineNodeTitle,
  initialContent = '',
  wordCountTarget = 300,
  onSave,
  onCancel,
}) => {
  const [content, setContent] = useState(initialContent);
  const [selectedText, setSelectedText] = useState('');
  const [cursorPosition, setCursorPosition] = useState(0);
  const [wordCount, setWordCount] = useState(0);
  const [showCompletion, setShowCompletion] = useState(false);
  const [completionSuggestions, setCompletionSuggestions] = useState<string[]>([]);
  const [undoStack, setUndoStack] = useState<string[]>([]);
  const [redoStack, setRedoStack] = useState<string[]>([]);
  const [isEditing, setIsEditing] = useState(true);

  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const completionTimeoutRef = useRef<NodeJS.Timeout>();
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  // 计算字数
  useEffect(() => {
    const count = content.trim().split(/\s+/).filter(Boolean).length;
    setWordCount(count);
  }, [content]);

  // 处理文本选择
  const handleSelection = useCallback(() => {
    if (!textareaRef.current) return;

    const start = textareaRef.current.selectionStart;
    const end = textareaRef.current.selectionEnd;

    if (start !== end) {
      const selected = content.substring(start, end);
      setSelectedText(selected);
    } else {
      setSelectedText('');
    }

    setCursorPosition(end);
  }, [content]);

  // 处理智能补全
  const handleCompletion = useCallback(async () => {
    if (!content || cursorPosition === 0) return;

    // 获取光标前的文本
    const textBeforeCursor = content.substring(0, cursorPosition);
    const lastWord = textBeforeCursor.split(/\s/).pop() || '';

    // 如果最后一个字符是触发字符
    if (lastWord.length > 2) {
      try {
        const completions = await aiCopilotService.getCompletion({
          currentText: content,
          cursorPosition,
          paragraphContext: outlineNodeTitle,
        });

        if (completions.length > 0) {
          setCompletionSuggestions(completions.map(c => c.text));
          setShowCompletion(true);
        }
      } catch (error) {
        console.error('Failed to get completions:', error);
      }
    }
  }, [content, cursorPosition, outlineNodeTitle]);

  // 监听内容变化，触发智能补全
  useEffect(() => {
    // 清除之前的超时
    if (completionTimeoutRef.current) {
      clearTimeout(completionTimeoutRef.current);
    }

    // 设置新的超时
    completionTimeoutRef.current = setTimeout(() => {
      handleCompletion();
    }, 500);

    return () => {
      if (completionTimeoutRef.current) {
        clearTimeout(completionTimeoutRef.current);
      }
    };
  }, [content, cursorPosition, handleCompletion]);

  // 应用补全建议
  const applyCompletion = (completion: string) => {
    const newContent = content.substring(0, cursorPosition) + completion + content.substring(cursorPosition);
    pushToUndoStack(content);
    setContent(newContent);
    setShowCompletion(false);

    // 移动光标到补全内容末尾
    setTimeout(() => {
      if (textareaRef.current) {
        const newPosition = cursorPosition + completion.length;
        textareaRef.current.setSelectionRange(newPosition, newPosition);
        textareaRef.current.focus();
      }
    }, 0);
  };

  // 应用Copilot建议
  const handleApplySuggestion = (suggestion: CopilotSuggestion) => {
    pushToUndoStack(content);

    if (suggestion.action === 'continue') {
      // 继续写作
      message.info('正在生成续写内容...');
      // TODO: 调用AI生成续写
    } else if (suggestion.action === 'expand' && suggestion.targetText) {
      // 扩展选中文本
      const expanded = `${suggestion.targetText}\n\n[这里添加更多细节和说明...]`;
      const newContent = content.replace(suggestion.targetText, expanded);
      setContent(newContent);
    } else if (suggestion.action === 'simplify' && suggestion.targetText) {
      // 简化文本
      message.info('正在简化文本...');
      // TODO: 调用AI简化文本
    }

    message.success('已应用建议');
  };

  // 撤销/重做
  const pushToUndoStack = (currentContent: string) => {
    setUndoStack(prev => [...prev, currentContent]);
    setRedoStack([]);
  };

  const handleUndo = () => {
    if (undoStack.length > 0) {
      const previousContent = undoStack[undoStack.length - 1];
      setUndoStack(prev => prev.slice(0, -1));
      setRedoStack(prev => [...prev, content]);
      setContent(previousContent);
    }
  };

  const handleRedo = () => {
    if (redoStack.length > 0) {
      const nextContent = redoStack[redoStack.length - 1];
      setRedoStack(prev => prev.slice(0, -1));
      setUndoStack(prev => [...prev, content]);
      setContent(nextContent);
    }
  };

  // 快捷键处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+Z 撤销
      if (e.ctrlKey && e.key === 'z' && !e.shiftKey) {
        e.preventDefault();
        handleUndo();
      }
      // Ctrl+Y 或 Ctrl+Shift+Z 重做
      if ((e.ctrlKey && e.key === 'y') || (e.ctrlKey && e.shiftKey && e.key === 'z')) {
        e.preventDefault();
        handleRedo();
      }
      // Tab 接受补全
      if (e.key === 'Tab' && showCompletion && completionSuggestions.length > 0) {
        e.preventDefault();
        applyCompletion(completionSuggestions[0]);
      }
      // Esc 关闭补全
      if (e.key === 'Escape') {
        setShowCompletion(false);
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [showCompletion, completionSuggestions, content]);

  // 获取上下文信息
  const getContextInfo = () => {
    const beforeText = content.substring(Math.max(0, cursorPosition - 200), cursorPosition);
    const afterText = content.substring(cursorPosition, Math.min(content.length, cursorPosition + 200));
    return { beforeText, afterText };
  };

  // 格式化工具菜单
  const formatMenu = (
    <Menu>
      <Menu.Item key="bold" icon={<FormatPainterOutlined />}>
        加粗
      </Menu.Item>
      <Menu.Item key="italic" icon={<FormatPainterOutlined />}>
        斜体
      </Menu.Item>
      <Menu.Item key="quote" icon={<FormatPainterOutlined />}>
        引用
      </Menu.Item>
      <Menu.Item key="list" icon={<FormatPainterOutlined />}>
        列表
      </Menu.Item>
    </Menu>
  );

  return (
    <div className="enhanced-paragraph-editor">
      <Row gutter={[16, 16]}>
        {/* 主编辑区 */}
        <Col xs={24} lg={16}>
          <Card
            title={
              <Space>
                <EditOutlined />
                <span>{outlineNodeTitle}</span>
              </Space>
            }
            extra={
              <Space>
                <Tooltip title="撤销">
                  <Button
                    icon={<UndoOutlined />}
                    onClick={handleUndo}
                    disabled={undoStack.length === 0}
                  />
                </Tooltip>
                <Tooltip title="重做">
                  <Button
                    icon={<RedoOutlined />}
                    onClick={handleRedo}
                    disabled={redoStack.length === 0}
                  />
                </Tooltip>
                <Dropdown overlay={formatMenu} trigger={['click']}>
                  <Button icon={<FormatPainterOutlined />}>格式</Button>
                </Dropdown>
                <Button type="primary" icon={<SaveOutlined />} onClick={() => onSave?.(content)}>
                  保存
                </Button>
                <Button icon={<CloseOutlined />} onClick={onCancel}>
                  取消
                </Button>
              </Space>
            }
          >
            {/* 编辑器 */}
            <div className="editor-container">
              <textarea
                ref={textareaRef}
                className="paragraph-textarea"
                value={content}
                onChange={(e) => {
                  const newContent = e.target.value;
                  if (newContent !== content) {
                    pushToUndoStack(content);
                    setContent(newContent);
                  }
                }}
                onSelect={handleSelection}
                onKeyUp={handleSelection}
                onClick={handleSelection}
                placeholder="开始编写段落内容..."
                spellCheck={false}
              />

              {/* 智能补全浮层 */}
              {showCompletion && completionSuggestions.length > 0 && (
                <div className="completion-popup" style={{ top: cursorPosition }}>
                  <div className="completion-header">
                    <span>智能补全建议</span>
                    <Button
                      type="text"
                      size="small"
                      icon={<CloseOutlined />}
                      onClick={() => setShowCompletion(false)}
                    />
                  </div>
                  <div className="completion-list">
                    {completionSuggestions.map((suggestion, index) => (
                      <div
                        key={index}
                        className="completion-item"
                        onClick={() => applyCompletion(suggestion)}
                      >
                        <span className="completion-text">{suggestion}</span>
                        {index === 0 && <span className="completion-hint">Tab</span>}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* 字数统计 */}
            <div className="word-count-bar">
              <Space>
                <span>字数: {wordCount}</span>
                <span>目标: {wordCountTarget}</span>
                <div
                  className="word-count-progress"
                  style={{
                    width: '100px',
                    height: '4px',
                    background: '#f0f0f0',
                    borderRadius: '2px',
                    overflow: 'hidden',
                  }}
                >
                  <div
                    style={{
                      width: `${Math.min(100, (wordCount / wordCountTarget) * 100)}%`,
                      height: '100%',
                      background: wordCount >= wordCountTarget ? '#52c41a' : '#1890ff',
                      transition: 'width 0.3s',
                    }}
                  />
                </div>
                {wordCount >= wordCountTarget && <CheckOutlined style={{ color: '#52c41a' }} />}
              </Space>
            </div>
          </Card>
        </Col>

        {/* AI Copilot 侧边栏 */}
        {!isMobile && (
          <Col xs={0} lg={8}>
            <CopilotSidebar
              sessionId={sessionId}
              selectedText={selectedText}
              beforeText={getContextInfo().beforeText}
              afterText={getContextInfo().afterText}
              cursorPosition={cursorPosition}
              onApplySuggestion={handleApplySuggestion}
            />
          </Col>
        )}
      </Row>

      {/* 移动端浮动Copilot按钮 */}
      {isMobile && (
        <Tooltip title="AI助手">
          <Button
            type="primary"
            shape="circle"
            icon={<BulbOutlined />}
            size="large"
            className="mobile-copilot-button"
            onClick={() => message.info('AI助手功能即将推出')}
            style={{
              position: 'fixed',
              bottom: '20px',
              right: '20px',
              width: '56px',
              height: '56px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
            }}
          />
        </Tooltip>
      )}
    </div>
  );
};